<template>
    <div>
        <!-- 卡片区域 -->
        <el-card class="box-card">
            <el-row :gutter="20">
                <el-col :span="7">
                    <el-input placeholder="请输入内容" size="small"  v-model="queryInfo.username" class="input-with-select" clearable
                              @clear="getUserList">
                        <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
                    </el-input>
                </el-col>
                <el-col :span="4">
                    <el-button type="primary" size="small" @click="addDialogVisible = true">添加用户</el-button>
                    <el-button type="primary" size="small">切换微信用户</el-button>
                </el-col>
            </el-row>
            <el-table :data="userList" border stripe v-loading="loading"
                      element-loading-text="拼命加载中"
                      element-loading-spinner="el-icon-loading">
                <el-table-column type="index" label="#"></el-table-column>
                <el-table-column prop="username" label="姓名"></el-table-column>
                <el-table-column prop="role_name" label="角色"></el-table-column>
                <el-table-column prop="mobile" label="手机号"></el-table-column>
                <el-table-column prop="email" label="邮箱"></el-table-column>
                <el-table-column label="操作">
                    <template slot-scope="scope">
                        <el-tooltip effect="dark" content="编辑" placement="top" :enterable="false">
                            <el-button type="primary" icon="el-icon-edit"  size="mini"
                                       @click="showEditDialog(scope.row.id)"></el-button>
                        </el-tooltip>
                        <el-tooltip effect="dark" content="删除" placement="top" :enterable="false">
                            <el-button type="danger" icon="el-icon-delete" size="mini"
                                       @click="showDelDialog(scope.row.id)"></el-button>
                        </el-tooltip>
                        <el-tooltip effect="dark" content="分配角色" placement="top" :enterable="false">
                            <el-button type="warning" icon="el-icon-setting" size="mini" @click="setRole(scope.row)"></el-button>
                        </el-tooltip>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="queryInfo.page"
                    :page-sizes="[10, 20, 30, 40,50]"
                    :page-size="queryInfo.limit"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total">
            </el-pagination>
        </el-card>
        <!-- 添加用户的对话框 -->
        <el-dialog title="添加用户" :visible.sync="addDialogVisible" width="50%" @close="addDialogClose">
            <!--内容主题区 -->
            <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="70px" class="demo-ruleForm">
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="addForm.username"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input v-model="addForm.password" type="password"></el-input>
                </el-form-item>
                <el-form-item label="手机号" prop="mobile">
                    <el-input v-model="addForm.mobile"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="addForm.email"></el-input>
                </el-form-item>
                <el-form-item label="备注" prop="remark">
                    <el-input type="textarea" v-model="addForm.remark"></el-input>
                </el-form-item>
            </el-form>
            <!--底部按钮区 -->
            <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
        </el-dialog>
        <!-- 修改用户的Dialog -->
        <el-dialog title="修改用户" :visible.sync="editDialogVisible" width="50%" @close="editDialogClose">
            <el-form :model="editForm" :rules="editFormRule" ref="editFormRef" label-width="70px">
                <el-form-item label="用户名">
                    <el-input v-model="editForm.username" disabled></el-input>
                </el-form-item>
                <el-form-item label="手机号" prop="mobile">
                    <el-input v-model="editForm.mobile"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="editForm.email"></el-input>
                </el-form-item>
                <el-form-item label="备注">
                    <el-input type="textarea" v-model="editForm.remark"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
    <el-button @click="editDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="editUserInfo">确 定</el-button>
  </span>
        </el-dialog>

        <!-- 分配角色 -->
        <el-dialog title="分配角色" :visible.sync="setRoleDialogVisible" width="50%" @close="setRoleDialogClose">
            <div>
                <p>当前的用户：{{userInfo.username}}</p>
                <p>当前的角色：{{userInfo.role_name}}</p>
                <p>分配新角色：
                    <el-select v-model="selectRoleId" placeholder="请选择">
                        <el-option
                                v-for="item in roleList"
                                :key="item.id"
                                :label="item.title"
                                :value="item.id">
                        </el-option>
                    </el-select>
                </p>
            </div>
            <span slot="footer" class="dialog-footer">
        <el-button @click="setRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
      </span>
        </el-dialog>
    </div>
</template>

<script>
export default {
    data() {
        var checkEmail = (rule, value, callback) => {
            const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
            if (regEmail.test(value)) {
                return callback();
            }
            callback(new Error('请输入合法的邮箱地址'));
        }
        var checkMobile = (rule, value, callback) => {
            const regMobile = /^(0|86|17951)?(13[0-9]|15[0123456789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
            if (regMobile.test(value)) {
                return callback();
            }
            callback(new Error('请输入合法的手机'));
        }
        return {
            queryInfo: {
                username: '',
                limit: this.$global_limit,
                page: this.$global_page
            },
            loading:true,
            userList: [],
            //需要被分配的角色用户信息
            userInfo: {},
            roleList: [],
            total: 0,
            addDialogVisible: false,
            editDialogVisible: false,
            setRoleDialogVisible: false,
            addForm: {
                username: '',
                password: '',
                mobile: '',
                email: '',
                remark: ''
            },
            addFormRules: {
                username: [
                    {required: true, message: '请输入用户名', trigger: 'blur'},
                    {min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur'}
                ],
                password: [
                    {required: true, message: '请输入密码', trigger: 'blur'},
                    {min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur'}
                ],
                mobile: [
                    {required: true, message: '请输入手机号', trigger: 'blur'},
                    {validator: checkMobile, trigger: 'blur'}
                ],
                email: [
                    {required: true, message: '请输入邮箱', trigger: 'blur'},
                    {validator: checkEmail, trigger: 'blur'}
                ]

            },
            editForm: {},
            editFormRule: {
                mobile: [
                    {required: true, message: '请输入手机号', trigger: 'blur'},
                    {validator: checkMobile, trigger: 'blur'}
                ],
                email: [
                    {required: true, message: '请输入邮箱', trigger: 'blur'},
                    {validator: checkEmail, trigger: 'blur'}
                ]
            },
            selectRoleId: ''
        }
    },
    created() {
        this.getUserList()
    },
    methods: {
        async getUserList() {
            const {data: res} = await this.$http.get('admin/user_list', {params: this.queryInfo})
            if (res.code !== 200) return this.$message.error(res.data.message)
            this.userList = res.data.list
            this.total = res.data.totalCount
            this.loading = false
        },
        handleSizeChange(newSize) {
            this.queryInfo.limit = newSize
            this.getUserList()
        },
        handleCurrentChange(newPage) {
            this.queryInfo.page = newPage
            this.getUserList()
        },
        //表单重置
        addDialogClose() {
            this.$refs.addFormRef.resetFields()
        },
        editDialogClose() {
            this.$refs.editFormRef.resetFields()
        },
        //添加用户事件
        addUser() {
            this.$refs.addFormRef.validate(async valid => {
                if (!valid) return this.$message.error('输入不合法')
                const {data: result} = await this.$http.post('admin/user_save', this.addForm)
                if (result.code !== 200) return this.$message.error(result.data.message)
                this.$message.success('添加用户成功')
                this.addDialogVisible = false
                this.getUserList()
            })

        },
        //获取用户信息
        async showEditDialog(id) {
            //结构赋值
            const {data: res} = await this.$http.get('admin/update_show/' + id)
            if (res.code !== 200) return this.$message.error(res.data.message)
            this.editForm = res.data.list;
            this.editDialogVisible = true;
        },
        //编辑用户
        editUserInfo() {
            this.$refs.editFormRef.validate(async valid => {
                if (!valid) return this.$message.error('输入不合法')
                const {data: result} = await this.$http.post('admin/user_save', {
                    id: this.editForm.id,
                    username: this.editForm.username,
                    mobile: this.editForm.mobile,
                    email: this.editForm.email,
                    remark: this.editForm.remark
                })
                if (result.code !== 200) return this.$message.error(result.data.message)
                this.$message.success('编辑用户成功')
                this.editDialogVisible = false
                this.getUserList()
            })
        },
        //删除用户
        async showDelDialog(id) {
            const configResult = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).catch(err => err);
            if (configResult !== 'confirm') return this.$message.info('已取消删除')
            const {data: result} = await this.$http.get('admin/user_delete/' + id)
            if (result.code !== 200) return this.$message.error(result.data.message)
            this.$message.success('删除成功')

            //删除成功后页码改变返还为上一页
            let totalPage = Math.ceil((this.total - 1) / this.queryInfo.limit);
            let currentPage = this.queryInfo.page > totalPage ? totalPage : this.queryInfo.page;
            this.queryInfo.page = this.queryInfo.page < 1 ? 1 : currentPage;

            this.getUserList();

        },
        async setRole(userInfo) {
            this.userInfo = userInfo
            //在展示对话框之前获取所有角色的列表
            const {data: result} = await this.$http.get('admin/role_info_list')
            if (result.code !== 200) return this.$message.error(result.data.message)
            this.roleList = result.data.list
            this.setRoleDialogVisible = true
        },
        //点击按钮
        async saveRoleInfo() {
            if (!this.selectRoleId) {
                return this.$message.error("请选择分配角色")
            }
            const {data: res} = await this.$http.post('admin/set_role_user_pivot', {
                uid: this.userInfo.id, group_id: this.selectRoleId+''
            })
            if (res.code !== 200) return this.$message.error(res.data.message)
            this.$message.success("分配成功")
            this.setRoleDialogVisible = false
            this.getUserList();

        },
        setRoleDialogClose(){
            this.selectRoleId = ''
            this.userInfo = {}
        }
    }
}
</script>

<style scoped>

</style>
